import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { ACCESS_TOKEN } from '@/utils/constants'
import storage from 'store'

export default class IWebSocket {
  constructor(stockFun, userFun, stockURL) {
    this.stompClient = null
    this.stockFun = stockFun
    this.userFun = userFun
    this.stockURL = stockURL
    this.init()
  }
  init() {
    const socket = new SockJS(process.env.VUE_APP_API_WSS_URL + (this.stockURL || '/wss'))
    
    const stompClient = Stomp.over(socket)
    stompClient.debug = () => {}
    // const headers = {}
    const connectCallback = () => {
      if (this.stockFun) {
        stompClient.subscribe('/topic/price', (msg) => {
          this.stockFun(JSON.parse(msg.body))
        })
      }
      
      if (this.userFun) {
        console.log('userFun');
        
        stompClient.subscribe(`?token=${storage.get(ACCESS_TOKEN)}`, (msg) => {
          this.userFun(JSON.parse(msg.body))
        })
      }
    }

    const errorCallback = (err) => {
      console.log(err)
    }

    stompClient.connect({}, connectCallback, errorCallback)
    this.stompClient = stompClient
  }
}
